<template>
  <div class="configuration">
    <!-- 页面头部：使用通用PageHeader组件 -->
    <page-header title="系统配置" subtitle="配置网站的基本信息、SEO信息、功能开关等">
      <template #right>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          <el-icon><Check /></el-icon>
          <span>保存配置</span>
        </el-button>
        <el-button @click="handleReset">
          <el-icon><RefreshRight /></el-icon>
          <span>重置</span>
        </el-button>
      </template>
    </page-header>

    <!-- 主内容区：可滚动容器 -->
    <div class="page-content">
      <el-scrollbar>
        <!-- 瀑布流布局：垂直排列的折叠卡片 -->
        <div class="content-flow">
          <!-- 基础配置卡片 -->
          <config-card
            title="基础配置"
            description="配置网站的基本信息"
            icon="Setting"
            :collapsed="collapsedSections.basic"
            @toggle="toggleSection('basic')"
          >
            <el-form ref="formBasicRef" :model="formData" :rules="rules" label-position="top">
              <!-- 系统标题 -->
              <el-row :gutter="24">
                <el-col :span="24">
                  <el-form-item label="系统标题" prop="title">
                    <el-input
                      v-model="formData.title"
                      placeholder="请输入系统标题"
                      maxlength="50"
                      show-word-limit
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 系统Logo和Favicon -->
              <el-row :gutter="24">
                <el-col :lg="12" :sm="24">
                  <el-form-item label="系统Logo" prop="logo">
                    <media-upload
                      v-model="formData.logo"
                      type="logo"
                      @preview="handleLogoPreview"
                      @remove="handleLogoRemove"
                    />
                  </el-form-item>
                </el-col>
                <el-col :lg="12" :sm="24">
                  <el-form-item label="Favicon" prop="favicon">
                    <media-upload
                      v-model="formData.favicon"
                      type="favicon"
                      @preview="handleFaviconPreview"
                      @remove="handleFaviconRemove"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </config-card>

          <!-- SEO配置卡片 -->
          <config-card
            title="SEO配置"
            description="配置搜索引擎优化相关信息"
            icon="Share"
            :collapsed="collapsedSections.seo"
            @toggle="toggleSection('seo')"
          >
            <el-form ref="formSeoRef" :model="formData" :rules="rules" label-position="top">
              <el-form-item label="系统关键词" prop="keywords">
                <el-input
                  v-model="formData.keywords"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入系统关键词，多个关键词用英文逗号分隔"
                  maxlength="200"
                  show-word-limit
                />
                <div class="form-tips">
                  <el-icon><InfoFilled /></el-icon>
                  关键词将用于网站的 meta 标签，有助于搜索引擎优化
                </div>
              </el-form-item>

              <el-form-item label="系统描述" prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入系统描述"
                  maxlength="500"
                  show-word-limit
                />
                <div class="form-tips">
                  <el-icon><InfoFilled /></el-icon>
                  系统描述将用于网站的 meta 标签，是搜索引擎展示的主要内容
                </div>
              </el-form-item>
            </el-form>
          </config-card>

          <!-- 功能配置卡片 -->
          <config-card
            title="功能配置"
            description="配置网站功能的开启状态"
            icon="Operation"
            :collapsed="collapsedSections.feature"
            @toggle="toggleSection('feature')"
          >
            <div class="switch-list">
              <div class="switch-item">
                <div class="switch-info">
                  <h4>开启评论</h4>
                  <p>开启后文章可以进行评论</p>
                </div>
                <el-switch
                  v-model="formData.enableComment"
                  active-color="var(--el-color-primary)"
                  inactive-color="var(--el-text-color-placeholder)"
                />
              </div>

              <div class="switch-item">
                <div class="switch-info">
                  <h4>评论审核</h4>
                  <p>开启后评论需要管理员审核通过才能显示</p>
                </div>
                <el-switch
                  v-model="formData.commentAudit"
                  active-color="var(--el-color-primary)"
                  inactive-color="var(--el-text-color-placeholder)"
                />
              </div>

              <div class="switch-item">
                <div class="switch-info">
                  <h4>开启注册</h4>
                  <p>开启后游客可以注册成为会员</p>
                </div>
                <el-switch
                  v-model="formData.enableRegister"
                  active-color="var(--el-color-primary)"
                  inactive-color="var(--el-text-color-placeholder)"
                />
              </div>
            </div>
          </config-card>

          <!-- 版权配置卡片 -->
          <config-card
            title="版权配置"
            description="配置网站底部显示的版权信息"
            icon="CopyDocument"
            :collapsed="collapsedSections.copyright"
            @toggle="toggleSection('copyright')"
          >
            <el-form ref="formCopyrightRef" :model="formData" :rules="rules" label-position="top">
              <el-row :gutter="24">
                <el-col :lg="12" :sm="24">
                  <el-form-item label="版权信息" prop="copyright">
                    <el-input
                      v-model="formData.copyright"
                      placeholder="请输入版权信息"
                      maxlength="100"
                      show-word-limit
                      clearable
                    />
                    <div class="form-tips">
                      <el-icon><InfoFilled /></el-icon>
                      支持HTML，例如：Copyright © {{ new Date().getFullYear() }}
                      <a href="https://example.com">example.com</a> All Rights Reserved.
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :lg="12" :sm="24">
                  <el-form-item label="备案信息" prop="icp">
                    <el-input
                      v-model="formData.icp"
                      placeholder="请输入备案信息"
                      maxlength="50"
                      show-word-limit
                      clearable
                    />
                    <div class="form-tips">
                      <el-icon><InfoFilled /></el-icon>
                      如 "京ICP备XXXXXXXX号"，将显示在网站底部
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </config-card>
        </div>
      </el-scrollbar>
    </div>

    <!-- 图片预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="图片预览"
      width="500px"
      align-center
      destroy-on-close
    >
      <div class="preview-dialog-content">
        <el-image :src="previewUrl" fit="contain" style="width: 100%; max-height: 400px" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, markRaw, computed, defineAsyncComponent, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Setting,
  Share,
  Operation,
  CopyDocument,
  Check,
  RefreshRight,
  InfoFilled,
  ArrowDown,
} from '@element-plus/icons-vue'

// 异步加载组件以优化性能
const ConfigCard = defineAsyncComponent(() => import('./components/ConfigCard.vue'))
const MediaUpload = defineAsyncComponent(() => import('./components/MediaUpload.vue'))

/**
 * 图标映射 - 将字符串映射到图标组件
 * 用于动态组件中使用字符串指定图标
 */
const iconMap = {
  Setting: markRaw(Setting),
  Share: markRaw(Share),
  Operation: markRaw(Operation),
  CopyDocument: markRaw(CopyDocument),
  ArrowDown: markRaw(ArrowDown),
}

/**
 * 状态管理
 */
// 加载状态
const loading = ref(false)

// 预览状态
const previewVisible = ref(false)
const previewUrl = ref('')

// 区域折叠状态控制
const collapsedSections = ref({
  basic: false,
  seo: false,
  feature: false,
  copyright: false,
})

/**
 * 切换区域折叠状态
 * @param {string} section - 区域标识
 */
const toggleSection = (section) => {
  collapsedSections.value[section] = !collapsedSections.value[section]
}

/**
 * 表单引用
 * 使用分离的表单引用以支持独立验证
 */
const formBasicRef = ref(null)
const formSeoRef = ref(null)
const formCopyrightRef = ref(null)

/**
 * 表单数据
 * 集中管理所有配置表单数据
 */
const formData = ref({
  // 基础配置
  title: '',
  logo: '',
  favicon: '',

  // SEO配置
  keywords: '',
  description: '',

  // 功能配置
  enableComment: true,
  commentAudit: false,
  enableRegister: true,

  // 版权配置
  copyright: '',
  icp: '',
})

// 保存原始表单数据（用于重置）
const originalFormData = ref({})

/**
 * 表单校验规则
 * 定义各字段的验证规则
 */
const rules = {
  title: [
    { required: true, message: '请输入系统标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  keywords: [{ required: true, message: '请输入系统关键词', trigger: 'blur' }],
  description: [{ required: true, message: '请输入系统描述', trigger: 'blur' }],
}

/**
 * 预览图片
 * @param {string} url - 图片URL
 */
const previewImage = (url) => {
  previewUrl.value = url
  previewVisible.value = true
}

// Logo预览处理
const handleLogoPreview = () => previewImage(formData.value.logo)

// Favicon预览处理
const handleFaviconPreview = () => previewImage(formData.value.favicon)

/**
 * 删除Logo
 * 提示确认后删除Logo图片
 */
const handleLogoRemove = () => {
  ElMessageBox.confirm('确定要删除 Logo 吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      formData.value.logo = ''
      ElMessage.success('已删除 Logo')
    })
    .catch(() => {})
}

/**
 * 删除Favicon
 * 提示确认后删除Favicon图片
 */
const handleFaviconRemove = () => {
  ElMessageBox.confirm('确定要删除 Favicon 吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      formData.value.favicon = ''
      ElMessage.success('已删除 Favicon')
    })
    .catch(() => {})
}

/**
 * 提交表单
 * 验证所有表单区域并提交数据
 */
const handleSubmit = async () => {
  try {
    // 收集所有表单的验证Promise
    const promises = [
      formBasicRef.value?.validate(),
      formSeoRef.value?.validate(),
      formCopyrightRef.value?.validate(),
    ].filter(Boolean)
    // 并行验证所有表单
    await Promise.all(promises)
    loading.value = true

    // TODO: 调用保存API
    console.log('表单数据:', formData.value)

    // 模拟API调用延迟
    setTimeout(() => {
      ElMessage.success('保存成功')
      loading.value = false
    }, 800)
  } catch (error) {
    console.error(error)
    ElMessage.error('表单验证失败，请检查填写内容')
    loading.value = false
  }
}

/**
 * 重置表单
 * 重新拉取配置并重置所有表单数据
 */
const handleReset = () => {
  ElMessageBox.confirm('确定要重置所有配置吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 重置所有表单区域
      formBasicRef.value?.resetFields()
      formSeoRef.value?.resetFields()
      formCopyrightRef.value?.resetFields()
      ElMessage.success('已重置所有配置')
    })
    .catch(() => {})
}
</script>

<style lang="scss" scoped>
/**
 * 配置页面整体样式
 */
.configuration {
  height: 100%;
  background-color: var(--el-bg-color-page);
  display: flex;
  flex-direction: column;
  padding: 24px 24px 0;

  /**
   * 主内容区域
   * 占用剩余空间并提供滚动能力
   */
  .page-content {
    flex: 1; /* 占用所有剩余空间 */
    min-height: 0; /* 允许内容正常滚动 */
    margin-top: 24px;
    overflow: hidden;

    .el-scrollbar {
      height: 100%;
    }

    /**
     * 瀑布流布局容器
     */
    .content-flow {
      display: flex;
      flex-direction: column;
      gap: 24px;
      padding-bottom: 24px;
    }
  }
}

/**
 * 功能开关列表样式
 */
.switch-list {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .switch-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    background: var(--el-fill-color-blank);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 12px;
    transition: all 0.3s ease;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);

    &:hover {
      border-color: var(--el-border-color);
      background: var(--el-color-primary-light-9);
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
    }

    .switch-info {
      h4 {
        margin: 0;
        font-size: 15px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      p {
        margin: 6px 0 0;
        font-size: 13px;
        color: var(--el-text-color-secondary);
      }
    }
  }
}

/**
 * 表单提示信息样式
 */
.form-tips {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  margin-top: 8px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
  line-height: 1.5;
  background-color: var(--el-color-info-light-9);
  padding: 8px 12px;
  border-radius: 6px;

  .el-icon {
    margin-top: 2px;
    color: var(--el-color-info);
    font-size: 14px;
  }

  a {
    color: var(--el-color-primary);
    text-decoration: none;
    transition: all 0.3s;

    &:hover {
      color: var(--el-color-primary-light-3);
      text-decoration: underline;
    }
  }
}

/**
 * 表单控件样式优化
 */
:deep(.el-form-item) {
  margin-bottom: 24px;

  .el-form-item__label {
    font-weight: 500;
    padding-bottom: 8px;
  }

  .el-input__wrapper,
  .el-textarea__inner {
    box-shadow: 0 0 0 1px var(--el-border-color) inset;
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 0 0 1px var(--el-border-color-darker) inset;
    }

    &.is-focus {
      box-shadow: 0 0 0 1px var(--el-color-primary) inset !important;
    }
  }

  .el-input__wrapper {
    padding: 1px 15px;
  }
}

/**
 * 响应式适配
 * 调整小屏幕设备的布局和样式
 */
@media (max-width: 768px) {
  .configuration {
    padding: 16px 16px 0;
  }

  .switch-item {
    padding: 16px !important;

    .switch-info {
      p {
        font-size: 12px !important;
      }
    }
  }

  .form-tips {
    padding: 6px 10px;
    font-size: 12px;
  }
}
</style>
